package com.example.threadPool;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.*;

public class Tpool3 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // 创建一个固定大小的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        // execute 无返回值
        executorService.execute(() -> System.out.println("execute执行：" + Thread.currentThread().getName()));

        // submit Runnable
        Future<?> submit = executorService.submit(() -> System.out.println("submit Runnable：" + Thread.currentThread().getName()));
        submit.get(); // 返回 null

        // submit Callable
        Future<Integer> future = executorService.submit(() -> 100 + 200);
        System.out.println("submit Callable 结果：" + future.get());

        // invokeAll
        // 提交一组任务，等待全部完成后再返回
        List<Callable<String>> callableList = Arrays.asList(
                () -> "A",
                () -> "B",
                () -> "C"
        );
        List<Future<String>> futures = executorService.invokeAll(callableList);
        for (Future<String> future1 : futures) {
            System.out.println("invokeAll结果：" + future1.get());
        }

        // invokeAny
        // 提交一组任务，只要有一个成功完成就返回其结果，其他任务会取消。
        String fastest = executorService.invokeAny(callableList);
        System.out.println("invokeAny最快结果：" + fastest);

        // 关闭线程池
        executorService.shutdown();

        // 配合 shutdown() 使用，等待所有任务在指定时间内完成，返回是否完成。
        if (executorService.awaitTermination(5, TimeUnit.SECONDS)) {
            System.out.println("线程池已关闭");
        }

    }
}
